package com.luo.d3s.ext.aop.exception.aspect;

import com.luo.d3s.ext.aop.config.D3sAopConsts;
import com.luo.d3s.ext.aop.config.D3sAopProps;
import com.luo.d3s.ext.aop.exception.handler.D3sExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;

/**
 * Controller日志AOP增强切面
 *
 * @author luohq
 * @date 2023-01-29 09:57
 */
@ConditionalOnProperty(prefix = D3sAopProps.PREFIX, name = "exception.enable-web-exception-handle", havingValue = "true", matchIfMissing = true)
@ControllerAdvice
public class D3sExceptionWebControllerAdvice {

    private Logger log = LoggerFactory.getLogger(D3sExceptionWebControllerAdvice.class);
    private D3sAopProps d3sAopProps;
    private D3sExceptionHandler d3sExceptionHandler;

    public D3sExceptionWebControllerAdvice(D3sAopProps d3sAopProps, D3sExceptionHandler d3sExceptionHandler) {
        this.d3sAopProps = d3sAopProps;
        this.d3sExceptionHandler = d3sExceptionHandler;
    }

    @PostConstruct
    void postConstruct() {
        log.info("D3s AOP EXT - WEB EXCEPTION ControllerAdvice- Started - configProps: {}", D3sAopConsts.WEB_MVC_POINT, this.d3sAopProps.getException());
    }

    /**
     * Controller异常处理
     *
     * @param request 请求
     * @param ex      异常
     * @return 响应结果
     */
    @ExceptionHandler({Throwable.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public Object handleException(HttpServletRequest request, Throwable ex) {
        log.warn("{}:{} - HandleException - {}", request.getMethod(), request.getServletPath(), String.valueOf(ex));
        return this.d3sExceptionHandler.handleException(null, ex);
    }
}